const express = require('express')

//导入数据库
const mongo = require('./mongoose/mongo')

const router = express.Router()

//设置全局id数
let id = null

router.get('/datas', (req, res) => {
  mongo.find({}, (err, val) => {
    if (err) {
      return console.log('拿去数据失败');
    }

    //获取最新的id
    for (item of val) {
      id = item.id
    }
    //然后自增1
    id++

    res.send(val)
  })
})


//添加数据
router.post('/newdata', (req, res) => {

  //往数据库添加数据
  const new_data = new mongo({
    id,
    name: req.body.name,
    age: req.body.age,
    tittle: req.body.tittle,
    times: new Date()
  })
  new_data.save()

  res.send({
    state: 200,
    message: '发送成功'
  })
})

//删除数据
router.get("/del", (req, res) => {
  console.log(req.query);

  mongo.deleteOne(req.query, (err) => {
    if (err) {
      return res.send({
        state: 404,
        message: '删除数据失败'
      })
    }
    res.send({
      state: 200,
      message: '发送成功'
    })
  })

})

//获取id 查找对应的数据
router.post('/id', (req, res) => {
  console.log(req.body.data);

  mongo.find({
    id: req.body.data
  }, (err, val) => {
    if (err) {
      return res.send({
        state: 404,
        message: "查找失败"
      })
    }
    res.send({
      state: 200,
      message: "查找成功",
      data: val
    })
  })
})

module.exports = router